package com.free.semantic.infrastruct.repository.impl;

import com.free.semantic.infrastruct.common.UserDO;
import com.free.semantic.infrastruct.mapper.UserMapper;
import com.free.semantic.infrastruct.mapper.SemanticNetworkMapper;
import com.free.semantic.infrastruct.repository.SemanticNetworkRepository;
import com.free.semantic.infrastruct.repository.UserRepository;
import com.free.semantic.model.conceptmodel.User;
import com.free.semantic.model.conceptmodel.SemanticNetwork;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserRepositoryImpl implements UserRepository {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private SemanticNetworkMapper semanticNetworkMapper;
    
    @Autowired
    private SemanticNetworkRepository semanticNetworkRepository;

    @Override
    public User findById(Long id) {
        UserDO userDO = userMapper.findById(id);
        if (userDO == null) {
            return null;
        }
        
        User user = convertToModel(userDO);
        // 查询用户的所有语义网络
        List<SemanticNetwork> networks = semanticNetworkRepository.findByUserId(id);
        user.setSemanticNetworks(networks);
        
        return user;
    }

    @Override
    public User findByUsername(String username) {
        UserDO userDO = userMapper.findByUsername(username);
        if (userDO == null) {
            return null;
        }
        
        User user = convertToModel(userDO);
        // 查询用户的所有语义网络
        List<SemanticNetwork> networks = semanticNetworkRepository.findByUserId(user.getId());
        user.setSemanticNetworks(networks);
        
        return user;
    }

    @Override
    public List<User> findAll() {
        List<UserDO> userDOs = userMapper.findAll();
        return userDOs.stream()
                .map(this::convertToModel)
                .collect(Collectors.toList());
    }

    @Override
    public Long save(User user) {
        UserDO userDO = convertToDO(user);
        userMapper.insert(userDO);
        return userDO.getId();
    }

    @Override
    public void update(User user) {
        UserDO userDO = convertToDO(user);
        userMapper.update(userDO);
    }

    @Override
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }
    
    private User convertToModel(UserDO userDO) {
        User user = new User();
        user.setId(userDO.getId());
        user.setUsername(userDO.getUsername());
        user.setPassword(userDO.getPassword());
        user.setSemanticNetworks(new ArrayList<>());
        return user;
    }
    
    private UserDO convertToDO(User user) {
        UserDO userDO = new UserDO();
        userDO.setId(user.getId());
        userDO.setUsername(user.getUsername());
        userDO.setPassword(user.getPassword());
        return userDO;
    }
} 